package com.jin_mo.custom.webView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.moudle.custom.R;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

/**
 * @ProjectName: ModuleDev
 * @Package: com.jin_mo.custom.webView
 * @Description:
 * @Author: sz_ijj
 * @CreateDate: 2021/12/22 9:42
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/12/22
 * @UpdateRemark: 更新说明
 */
public class BrowserActivity extends AppCompatActivity
        implements StatusAction, HandlerAction {

    private static final String INTENT_KEY_IN_URL = "INTENT_KEY_IN_URL";
    private static final String INTENT_KEY_IN_URL_TITLE = "INTENT_KEY_IN_URL_TITLE";


    public static void start(Context context, String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Intent intent = new Intent(context, BrowserActivity.class);
        intent.putExtra(INTENT_KEY_IN_URL_TITLE, "");
        intent.putExtra(INTENT_KEY_IN_URL, url);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void start(Context context, String url,String title) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Intent intent = new Intent(context, BrowserActivity.class);
        intent.putExtra(INTENT_KEY_IN_URL, url);
        intent.putExtra(INTENT_KEY_IN_URL_TITLE, title);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    private StatusLayout mStatusLayout;
    private ProgressBar mProgressBar;
    private SmartRefreshLayout mRefreshLayout;
    private BrowserView mBrowserView;
    private TextView mTvTitle;
    private ImageView mBack;
    private String mUrlTitle = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browser);
        initView();
        initData();

    }

    /**
     * 初始化控件
     */
    private void initView() {
        mStatusLayout = findViewById(R.id.hl_browser_hint);
        mProgressBar = findViewById(R.id.pb_browser_progress);
        mRefreshLayout = findViewById(R.id.sl_browser_refresh);
        mBrowserView = findViewById(R.id.wv_browser_view);
        mTvTitle = findViewById(R.id.tv_browser_title);
        mBack = findViewById(R.id.iv_browser_back);

        // 设置 WebView 生命管控
        mBrowserView.setLifecycleOwner(this);

        // 设置网页刷新监听
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                reload();
            }
        });

        mBack.setOnClickListener(v -> finish());
    }

    /**
     * 初始化数据
     */
    private void initData() {
        showLoading();

        mTvTitle.setText("正在加载中...");
        String url = getIntent().getStringExtra(INTENT_KEY_IN_URL);
        mUrlTitle = getIntent().getStringExtra(INTENT_KEY_IN_URL_TITLE);
        mBrowserView.setBrowserViewClient(new AppBrowserViewClient());
        mBrowserView.setBrowserChromeClient(new AppBrowserChromeClient(mBrowserView));
        mBrowserView.loadUrl(url);
    }

    @Override
    public StatusLayout getStatusLayout() {
        return mStatusLayout;
    }


    /**
     * 重新加载当前页
     */
    private void reload() {
        mBrowserView.reload();
    }

    private class AppBrowserViewClient extends BrowserView.BrowserViewClient {

        /**
         * 网页加载错误时回调，这个方法会在 onPageFinished 之前调用
         */
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // 这里为什么要用延迟呢？因为加载出错之后会先调用 onReceivedError 再调用 onPageFinished
            post(() -> showError(listener -> reload()));
        }

        /**
         * 开始加载网页
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mProgressBar.setVisibility(View.VISIBLE);
        }

        /**
         * 完成加载网页
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            mProgressBar.setVisibility(View.GONE);
            mRefreshLayout.finishRefresh();
            showComplete();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeCallbacks();
    }

    private class AppBrowserChromeClient extends BrowserView.BrowserChromeClient {

        private AppBrowserChromeClient(BrowserView view) {
            super(view);
        }

        /**
         * 收到网页标题
         */
        @Override
        public void onReceivedTitle(WebView webView, String title) {
            if (TextUtils.isEmpty(title)) {
                mTvTitle.setText("标题获取失败");
                return;
            }
            if (!TextUtils.isEmpty(title) &&!webView.getUrl().contains(title) && TextUtils.isEmpty(mUrlTitle)) {
                mTvTitle.setText(title);
            } else {
                mTvTitle.setText(mUrlTitle);
            }
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            if (icon == null) {
                return;
            }
            //右侧icon
        }

        /**
         * 收到加载进度变化
         */
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgressBar.setProgress(newProgress);
        }
    }
}
